package com.fangzhi;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


public class PaChong {
    /**
     * 保存的Excel地址
     */
    public static final String excelFilePath = "/Users/edy/yhqx_data/file.xlsx";
    /**
     * 当前的城市id
     */
    public static final String cityId = "0101";
    /**
     * 从第几页开始  默认为0
     */
    public static Integer pageNo = 326;
    /**
     * 秘钥
     */
    public static final String cookieString = "H5CookieId=ecc40157-2104-4758-9e47-8ee93f4ac55e; firsttime=1726901343046; CookieGuid=dacef390-5762-4dfe-834f-02655d1231f5; Esid=8d1c5abf-534e-4a79-bc06-ce21b96c08a3; Lgid=LRpRtrsC3gsExwGXhEk%2FlpaR3waA7McUH7SGryL5%2FSHD7YLB5yVeWD7L4y1OicTH6Fhib5V691ng1RuOz3HLKR6CCgXWwFSAceAygi9Sc8RPVP4Z277EJVye0XhJG0lUurqgE0dgDITTu5Li5wFzlg%3D%3D; tcUser=%7B%22AccessToken%22%3A%227AB7B638BB97A46CE1AF9F98DEE4B1D1%22%2C%22MemberId%22%3A%2274cac13019f3f21ac633548bde47fc3d%22%7D; H5Channel=bingseo%2CNormal; outerFrom=5000068; hotel_pc_AB=B; lasttime=1727076557835; JSESSIONID=C4EF86C92AC4AC0B47E74D852BAD0188";
    public static void main(String[] args) throws IOException {
        File file = new File(excelFilePath);
        if (!file.exists()) {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Data Sheet");
            List<String> text = new ArrayList<>();
            text.add("伟云纺织");
            int rowNum = 0;
            for (String data : text) {
                Row row = sheet.createRow(rowNum++);
                Cell cell = row.createCell(0);
                cell.setCellValue(data);
            }
            try (FileOutputStream fos = new FileOutputStream(excelFilePath)) {
                workbook.write(fos);
                workbook.close(); // 关闭Workbook资源
                fos.close(); // 关闭FileOutputStream资源（但在这里其实是不必要的，因为try-with-resources会自动处理）
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        getId(cityId);
    }


    public static void getId(String cityId){
        List<String> ids = new ArrayList<>();
        try {
            Integer pageSize = 0;
            do {
                String urlString = "https://www.elong.com/tapi/v2/list?city="+cityId+"&inDate=2024-09-23&outDate=2024-09-24&filterList=8888_1&keywords=&placename=&pageIndex="+pageNo+"&pageSize=20";
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 设置请求方法
                conn.setRequestMethod("GET");
                // 设置请求头
                conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
                conn.setRequestProperty("Connection", "keep-alive");
                conn.setRequestProperty("Sec-Fetch-Dest", "empty");
                conn.setRequestProperty("Sec-Fetch-Mode", "cors");
                conn.setRequestProperty("Sec-Fetch-Site", "same-origin");
                conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36");
                conn.setRequestProperty("accept", "application/json, text/plain, */*");
                conn.setRequestProperty("appfrom", "15");
                conn.setRequestProperty("currency", "HKD");
                conn.setRequestProperty("deviceid", "ecc40157-2104-4758-9e47-8ee93f4ac55e");
                conn.setRequestProperty("lang", "zh-cn");
                conn.setRequestProperty("sec-ch-ua", "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Google Chrome\";v=\"128\"");
                conn.setRequestProperty("sec-ch-ua-mobile", "?0");
                conn.setRequestProperty("sec-ch-ua-platform", "\"macOS\"");
                conn.setRequestProperty("timezone", "8");
                conn.setRequestProperty("tmapi-client", "epc");
                conn.setRequestProperty("traceid", "d668d584-5273-47cc-98e2-4614614605bc");
                conn.setRequestProperty("user-dun","x77xxxxxItiUQP+xIJPsWTdj6j5QS5CYhl8dWX7o85pxyjfDY6R7MdJUxvgCJkQ/x7xRxxsbxwPaVxwaRqY0WWKDOrPDx7HpivTl1vOaOPfBt+YdwEymJ7fwXXHYaXf3XeJdgl+/74H6ANcRbwrquySpE7P9xsWZiAMZYtMXxkQLIhmQ8Avq24mQmLgbN4Sf7NkBtKCqBTHwTNYXWpYBsKNB2vHwFU8DhhCRLqhd4pgqHbAd74cIIq8TtOk/8Tk9FcfBEUjI9lkktnhR9vrgJqhRFcY6a+h9XvoM2+CIFOMQY1ghW7NjYI7haB+WY7+QawlG67itlcseqa18HjF7dNHaHjMas31x7hLYsS89awAIzuc/CWerms+baB1vP2H4CtN7LsS0ipoB0/g3df2r75NQaBpJY5p06w+J76x2/bhGCe+QiXh937pjPzFstnd3/VVutLFNfiqSMnImzyzgYvm/PVEBKE///VTSKE///VTSKuwppoU34GRnpLUhgJ7jOo2QEbggaXPWux+baX+WjsoqgNzsfsPtx58J");
                // 将Cookie字符串转换为请求头
                conn.setRequestProperty("Cookie", cookieString);

                // 发送请求并读取响应
                if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                }
                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

                String output;
                StringBuilder sb = new StringBuilder();
                while ((output = br.readLine()) != null) {
                    sb.append(output);
                }
                conn.disconnect();
                date date = JSON.parseObject(sb.toString(), date.class);
                List<String> collect = date.getData().getHotelList().stream().map(T -> T.getHotelId()).collect(Collectors.toList());
                pageSize = date.getData().getHotelList().size();
                ids.addAll(collect);
                pageNo +=1;
                System.out.println("pageNo:"+pageNo);
                saveExcel(collect);
            }while (pageSize == 20);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(JSON.toJSONString(ids));
    }

    public static void saveExcel(List<String> stationIds) throws IOException, InterruptedException {
        List<String[]> excelData = new ArrayList<>();
        try {
            for (String stationId : stationIds) {
                System.out.print(stationId + ",");
                String path = "https://www.elong.com/hotel/hoteldetail?hotelId="+stationId+"&inDate=2024-09-21&outDate=2024-09-22&prc=594&sourcePage=&sourcePrice=";
                Connection connection = Jsoup.connect(path).header("cookie", cookieString)
                        .method(Connection.Method.GET);
                Document document = connection.execute().parse(); // 执行请求并解析响应
                Element div = document.select("div[data-v-4a25b5af]").first();
                String text1 = div.text();


                String[] text = new String[]{document.select("span[data-v-0e7e36d2]").text()
                        ,text1.substring(text1.indexOf("装修日期:") + 5, text1.indexOf("客房数量")).trim()
                        ,text1.substring(text1.indexOf("客房数量:") + 5, text1.indexOf("酒店类型")).trim()
                        ,text1.substring(text1.indexOf("联系电话") + 4, text1.indexOf("酒店描述")).trim()};
                excelData.add(text);
                Thread.sleep(4000);
            }
            saveData(excelData);
        }catch (Exception e){
            e.printStackTrace();
            saveExcel(stationIds);
        }

    }

    public static void saveData(List<String[]> text){
        File file = new File(excelFilePath);
        Workbook workbook;
        try {
            if (!file.exists()) {
                // 文件不存在，创建一个新的Workbook
                workbook = new XSSFWorkbook();
                Sheet sheet = workbook.createSheet("Sheet1");
            } else {
                // 文件存在，读取现有的Workbook
                try (FileInputStream fis = new FileInputStream(file)) {
                    workbook = WorkbookFactory.create(fis);
                }
            }

            // 获取或创建工作表
            Sheet sheet = workbook.getNumberOfSheets() > 0 ? workbook.getSheetAt(0) : workbook.createSheet("Sheet1");

            // 追加数据
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 0; i < text.size(); i++) {
                Row newRow = sheet.createRow(lastRowNum + 1 + i);
                Cell cell = newRow.createCell(0);
                cell.setCellValue(text.get(i)[0]);
                cell = newRow.createCell(1);
                cell.setCellValue(text.get(i)[1]);
                cell = newRow.createCell(2);
                cell.setCellValue(text.get(i)[2]);
                cell = newRow.createCell(3);
                cell.setCellValue(text.get(i)[3]);
            }

            // 写入文件
            try (FileOutputStream fos = new FileOutputStream(file)) {
                workbook.write(fos);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Data
    public static class date {
        private DateDto data;
        @Data
        public static class DateDto{
            private List<HotelList> hotelList;
            @Data
            public static class HotelList{
                private String hotelId;
            }
        }
    }
}
